package com.yixin.hospital.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.common.Constant;
import com.yixin.hospital.entity.bo.TemplateDetail;
import com.yixin.hospital.entity.domain.Template;
import com.yixin.hospital.entity.dto.req.template.TemplateAddReqDTO;
import com.yixin.hospital.entity.vo.ListTemplateVO;
import com.yixin.hospital.service.JobOfficeService;
import com.yixin.hospital.service.TemplateService;
import com.yixin.hospital.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/template")
@Api(value = "模板管理", tags = "模板管理")
@Slf4j
public class TemplateController {

    @Resource
    TemplateService templateService;
    @Resource
    JobOfficeService jobOfficeService;

    @GetMapping("/list")
    @ApiOperation(value = "查询科室模板")
    public ApiResult<?> list(@RequestParam(value = "jobOfficeId", required = false) Long jobOfficeId) {
        LambdaQueryWrapper<Template> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(jobOfficeId)) {
            queryWrapper.eq(Template::getJobOffice, jobOfficeId);
        }
        List<Template> templateList = templateService.list(queryWrapper);
        List<ListTemplateVO> list = new ArrayList<>();
        for (Template template : templateList) {
            ListTemplateVO listTemplateVO = new ListTemplateVO();
            listTemplateVO.setId(template.getId());
            listTemplateVO.setName(template.getName());
            listTemplateVO.setJobOffice(template.getJobOffice());
            listTemplateVO.setJobOfficeName(jobOfficeService.getById(template.getJobOffice()).getName());
            List<TemplateDetail> templateDetailList = new ArrayList<>();
            templateDetailList.addAll(JSON.parseObject(template.getDetail().toString(), new TypeReference<List<TemplateDetail>>() {
            }.getType()));
            listTemplateVO.setTemplateDetailList(templateDetailList);
            list.add(listTemplateVO);
        }
        return ApiResult.success(list);
    }

    @PostMapping("/addOrUpdate")
    @ApiOperation(value = "添加/编辑模板")
    public ApiResult<?> add(@Valid @RequestBody TemplateAddReqDTO templateAddReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        // 校验
        for (TemplateDetail templateDetail : templateAddReqDTO.getTemplateDetailList()) {
            if (StringUtils.isBlank(templateDetail.getColumn()) || templateDetail.getType() == null ||
                    templateDetail.getRequired() == null || (templateDetail.getType() == 2 && templateDetail.getTypeValues() == null) ) {
                return ApiResult.error("数据异常，请检查");
            }
        }
        // 添加
        if (templateAddReqDTO.getId() == null) {
            Template template = new Template();
            template.setJobOffice(templateAddReqDTO.getJobOffice());
            template.setName(templateAddReqDTO.getName());
            template.setDetail(new Gson().toJson(templateAddReqDTO.getTemplateDetailList()));
            template.setCreatedBy(userName);
            template.setUpdatedBy(userName);
            templateService.save(template);
            return ApiResult.success();
        }
        Template template = templateService.getById(templateAddReqDTO.getId());
        template.setJobOffice(templateAddReqDTO.getJobOffice());
        template.setName(templateAddReqDTO.getName());
        template.setDetail(new Gson().toJson(templateAddReqDTO.getTemplateDetailList()));
        template.setUpdatedBy(userName);
        templateService.updateById(template);
        return ApiResult.success();
    }

    @DeleteMapping("/remove/{id}")
    @ApiOperation(value = "删除模板")
    public ApiResult remove(@PathVariable int id) {
        templateService.removeById(id);
        return ApiResult.success();
    }
}
